package com.spongebob.magic_conch_backend.repository;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.Scanner;

public class OllamaService {

    private static final String OLLAMA_API_URL = "http://localhost:11434/api/generate";

    /**
     * 向 Ollama 的 generate 方法发送请求
     * @param model 要使用的模型名称
     * @param prompt 输入的提示词
     * @return AI 生成的回答
     */
    public String generateText(String model, String prompt) {
        // 构建请求 JSON 数据
        JSONObject requestJson = new JSONObject();
        requestJson.set("model", model);
        requestJson.set("prompt", prompt);

        // 发送 POST 请求
        HttpRequest httpRequest = HttpRequest.post(OLLAMA_API_URL)
                .header("Content-Type", "application/json")
                .body(requestJson.toString());

        // 获取响应流
        try (Scanner scanner = new Scanner(httpRequest.execute().bodyStream()).useDelimiter("\\A")) {
            StringBuilder responseBuilder = new StringBuilder();
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (!line.isEmpty()) {
                    // 解析每一行 JSON 数据，提取生成的文本
                    JSONObject responseJson = new JSONObject(line);
                    if (responseJson.containsKey("response")) {
                        responseBuilder.append(responseJson.getStr("response"));
                    }
                }
            }
            return responseBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "请求出错: " + e.getMessage();
        }
    }
}